package com.htzos.admin.system.controller;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import com.htzos.admin.system.bean.SystemRoleBase;
import com.htzos.admin.system.bean.SystemUserBase;
import com.htzos.admin.system.bean.SystemUserroleBase;
import com.htzos.admin.system.service.SystemRoleBaseService;
import com.htzos.admin.system.service.SystemRoleMenuService;
import com.htzos.admin.system.service.SystemUserBaseService;
import com.htzos.admin.system.service.SystemUserroleBaseService;
import com.htzos.base.parent.ctrl.BaseController;
import com.htzos.common.tool.ExtQueryBean;
import com.htzos.common.util.CommonUtil;
import com.htzos.common.util.PropertiesUtil;

@Controller
@RequestMapping("/systemUserBase")
public class SystemUserBaseController extends BaseController {

	//private Logger logger = Logger.getLogger(SystemUserBaseController.class);

	@Resource
	private SystemUserBaseService systemUserBaseService;
	@Resource
	private SystemRoleBaseService systemRoleBaseService;
	@Resource
	private SystemRoleMenuService systemRoleMenuService;
	@Resource
	private SystemUserroleBaseService systemUserroleBaseService;

	@RequestMapping(value="/list", method=RequestMethod.POST)
	public ModelAndView list(HttpServletRequest request, SystemUserBase condition, ExtQueryBean extQuery) {
		if (extQuery.getSize() == null) {
			extQuery.setSize(10);
		}
		if (extQuery.getPageNum() == null) {
			extQuery.setPageNum(1);
		}

		extQuery.setTotal(systemUserBaseService.systemUserBaseViewTotal(condition,
				extQuery));
		List<SystemUserBase> list = systemUserBaseService.systemUserBaseViewList(
				condition, extQuery);
		request.setAttribute("list", list);
		request.setAttribute("condition", condition);
		request.setAttribute("extQuery", extQuery);

		request.getSession(true).setAttribute("conditionStr", condition);
		request.getSession(true).setAttribute("extQueryStr", extQuery);
		
		return new ModelAndView("admin/system/systemUserBaseList");
	}
    
    @RequestMapping(value="/list", method=RequestMethod.GET)
    public ModelAndView listGet(HttpServletRequest request, SystemUserBase condition, ExtQueryBean extQuery, @RequestParam(value="s", required=false, defaultValue="0")Integer useSession) {
    	if(useSession == 1){
    		//使用Session里面的参数，通常是从update和insert跳转来的
    		HttpSession session = request.getSession();
    		if(session != null){
    			condition = (SystemUserBase) session.getAttribute("conditionStr");
    			extQuery = (ExtQueryBean) session.getAttribute("extQueryStr");
    		}
    	}

    	return list(request, condition, extQuery);
    }

	@RequestMapping("/dialogList")
    public String dialogList(HttpServletRequest request, SystemUserBase condition, ExtQueryBean extQuery) {
    	
    	request.setAttribute("tableName", "选择用户");
    	
        if(extQuery.getSize() == null) {
            extQuery.setSize(10);
        }
        if(extQuery.getPageNum() == null) {
            extQuery.setPageNum(1);
        }
    	
        condition.setActiveFlag(1);
		extQuery.setTotal(systemUserBaseService.systemUserBaseTotal(condition, extQuery));
		List<SystemUserBase> list = systemUserBaseService.systemUserBaseList(condition, extQuery);
		request.setAttribute("list", list);
		request.setAttribute("condition", condition);
		request.setAttribute("extQuery", extQuery);

		return "admin/system/systemUserBaseDialogList";
    }

    @RequestMapping("/logout")    
    public ModelAndView logout(HttpServletRequest request,SystemUserBase systemUserBase, ExtQueryBean extQuery) {
		request.getSession().removeAttribute("currentUser");
		request.getSession().removeAttribute("currentAgent");
		return new ModelAndView(new RedirectView("loginIndex"));
    }
    
	@RequestMapping("/update")
	public ModelAndView update(HttpServletRequest request, SystemUserBase systemUserBase, Integer[] userRole, String passwordEncrypt) {
		
		if(passwordEncrypt != null && !passwordEncrypt.isEmpty())
			systemUserBase.setPassword(passwordEncrypt);
		else
			systemUserBase.setPassword(null);

		systemUserBaseService.systemUserBaseUpdate(systemUserBase);

		SystemUserroleBase systemUserroleBase = new SystemUserroleBase();
		systemUserroleBase.setUserId(systemUserBase.getId());
		List<SystemUserroleBase> selectedRoles = systemUserroleBaseService.systemUserroleBaseList(systemUserroleBase, null);
		//删除旧权限
		for(SystemUserroleBase roleBase : selectedRoles){
			boolean del = true;
			for(Integer role : userRole){
				if(roleBase.getRoleId().intValue() == role.intValue()){
					del = false;
					break;
				}
			}
			
			if(del){
				systemUserroleBaseService.systemUserroleBaseDelete(roleBase);
			}
		}
		//添加新权限
		for(Integer role : userRole){
			boolean add = true;
			for(SystemUserroleBase roleBase : selectedRoles){
				if(roleBase.getRoleId().intValue() == role.intValue()){
					add = false;
					break;
				}
			}
			
			if(add){
				SystemUserroleBase addrole = new SystemUserroleBase();
				addrole.setUserId(systemUserBase.getId());
				addrole.setRoleId(role);
				systemUserroleBaseService.systemUserroleBaseInsert(addrole);
			}
		}
		
        return new ModelAndView(new RedirectView("list"), "s", 1);
	}

	@RequestMapping("/updatePage")
	public String updatePage(HttpServletRequest request, Integer id) {
		List<SystemRoleBase> list = systemRoleBaseService.systemRoleBaseList(null, null);
		request.setAttribute("roleList", list);
		SystemUserBase systemUserBase = systemUserBaseService.systemUserBaseGet(id);
		request.setAttribute("systemUserBase", systemUserBase);
		String[] selectedRoles = systemUserroleBaseService.systemUserroleBaseGetUserRoles(systemUserBase.getId());
		request.setAttribute("selectedRoles", JSONArray.fromObject(selectedRoles));
		
		return "admin/system/systemUserBaseUpdate";
	}

	@RequestMapping("/updatePassword")
	public String updatePassword(HttpServletRequest request) {
		request.setAttribute("message", request.getParameter("message"));
		return "admin/system/systemUserBasePasswordUpdate";
	}
	
    // 检测密码是否能过强度检测(正则表达式检测)
    // 要求密码长度最少8位最多25位，包含至少1个特殊字符，(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})
	//2个数字，2个大写字母和一些小写字母
    public static boolean checkPasswordStrangth(String username, String password) {
        if (username.equalsIgnoreCase(password)
            || password.toLowerCase().contains(username.toLowerCase())) {
            return false;
        }
        if (password.length() < 8) {
            return false;
        }
        /* 要求密码长度最少8位，包含至少1个特殊字符，1个数字，1个大写字母和一些小写字母 */
        String regexText = "(?=^.{8,25}$)(?=(?:.*?\\d){1})(?=.*[a-z])(?=(?:.*?[A-Z]){1})(?!.*\\s)[0-9a-zA-Z!@#$%*()_+^&]*$";
        return password.matches(regexText);
    }
    
	@RequestMapping("/savePassword")
	public ModelAndView savePassword(HttpServletRequest request, SystemUserBase systemUserBase, String oldPasswordEncrypt, String newPasswordEncrypt,RedirectAttributes attr) {
		SystemUserBase user = (SystemUserBase) request.getSession().getAttribute("currentUser");
		if(user == null || user.getId() == null){
			return new ModelAndView("redirect:/toLogin");
		}
		
		if(oldPasswordEncrypt == null || newPasswordEncrypt == null){
//			return new ModelAndView("exception","message","密码不能为空");
			attr.addAttribute("message", "密码不能为空！");
			return new ModelAndView(new RedirectView("../systemUserBase/updatePassword"));
		}

		SystemUserBase newpass = new SystemUserBase();
		newpass.setId(user.getId());
		newpass.setPassword(oldPasswordEncrypt);
		List<SystemUserBase> list = systemUserBaseService.systemUserBaseList(newpass, null);
		
		//判断是否查到对应的用户
		if(list.size()>0){
			//找到进行更新
			newpass.setPassword(newPasswordEncrypt);
			newpass.setFirstLogin(0);
			systemUserBaseService.systemUserBaseUpdate(newpass);
			if(user.getFirstLogin() == 1){
				user = systemUserBaseService.systemUserBaseGet(user.getId());
				request.getSession().setAttribute(CommonUtil.CURRENTUSER, user);
			}
			attr.addAttribute("message", "密码修改成功");
			return new ModelAndView(new RedirectView("../systemUserBase/updatePassword"));
		}else{
			//没找到进入错误页
//			return new ModelAndView("exception","message","原密码输入错误！");
			attr.addAttribute("message", "原密码输入错误！");
			return new ModelAndView(new RedirectView("../systemUserBase/updatePassword"));
		}
		
//		return "system/systemUserBaseUpdate";
	}
	
	@RequestMapping("/insert")
	public ModelAndView insert(HttpServletRequest request, SystemUserBase systemUserBase, Integer[] userRole, String passwordEncrypt) {
		try {
			String uuid = UUID.randomUUID().toString();
			systemUserBase.setUserId(uuid);
			systemUserBase.setPassword(passwordEncrypt);
			systemUserBaseService.systemUserBaseInsert(systemUserBase);
			
			//添加新权限
			for(Integer role : userRole){
				SystemUserroleBase addrole = new SystemUserroleBase();
				addrole.setUserId(systemUserBase.getId());
				addrole.setRoleId(role);
				systemUserroleBaseService.systemUserroleBaseInsert(addrole);
			}
		} catch (Exception e) {
			request.setAttribute("message", "添加失败，请检查输入，可能原因（1.违法输入；2.重复账号，3.程序异常）");
		    return new ModelAndView("exception");
		}
		
        return new ModelAndView(new RedirectView("list"), "s", 1);
	}
	
	@RequestMapping("/changeImg")
	public void fileuplaod(HttpServletRequest request, HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		Integer result=FAIL;
		try {
			String image=request.getParameter("image");
			if(image==null){
				result=FAIL;
			}else{
				//获取当前用户
				SystemUserBase user=(SystemUserBase) request.getSession().getAttribute(CommonUtil.CURRENTUSER);
				user.setImg(image);
				systemUserBaseService.systemUserBaseUpdate(user);
				request.getSession().setAttribute(CommonUtil.CURRENTUSER, user);
				result=SUCCESS;
			}
		} catch (Exception e1) {
			result=FAIL;
		}
		
		try{
			PrintWriter writer = response.getWriter();
			writer.print(result);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	@RequestMapping("/addPage")
	public String addPage(HttpServletRequest request) {
		List<SystemRoleBase> list = systemRoleBaseService.systemRoleBaseList(null, null);
		request.setAttribute("roleList", list);
		return "admin/system/systemUserBaseAdd";
	}

//	@RequestMapping("/delete")
//	public ModelAndView delete(HttpServletRequest request,
//			SystemUserBase systemUserBase) {
//		systemUserBaseService.systemUserBaseDelete(systemUserBase);
//
//		return new ModelAndView(new RedirectView("list"), "s", 1);
//	}
	
	@RequestMapping("/enable")
	public ModelAndView enable(HttpServletRequest request, Integer id) {
		SystemUserBase systemUserBase = new SystemUserBase();
		systemUserBase.setId(id);
		systemUserBase.setActiveFlag(1);
		systemUserBaseService.systemUserBaseUpdate(systemUserBase);

		return new ModelAndView(new RedirectView("list"), "s", 1);
	}

	@RequestMapping("/disable")
	public ModelAndView disable(HttpServletRequest request, Integer id) {
		SystemUserBase systemUserBase = new SystemUserBase();
		systemUserBase.setId(id);
		systemUserBase.setActiveFlag(0);
		systemUserBaseService.systemUserBaseUpdate(systemUserBase);

		return new ModelAndView(new RedirectView("list"), "s", 1);
	}

}